package com.ndp.fb.rdb.db.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.esotericsoftware.minlog.Log;
import com.ndp.fb.constant.CommonConstants;
import com.ndp.fb.rdb.api.EntrustAccountConnectionObjectsRdbService;
import com.ndp.fb.rdb.db.DaoTemplate;
import com.ndp.fb.rdb.db.impl.mapper.DefaultRowMapper;
import com.ndp.fb.rdb.model.EntrustAccountConnectionObjects;
import com.ndp.fb.redis.api.RedisDistributedLockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by infi on 2015/3/31.
 */
@Service
public class EntrustAccountConnectionObjectsRdbServiceImpl extends DaoTemplate implements EntrustAccountConnectionObjectsRdbService{

    @Autowired
    private RedisDistributedLockService redisDistributedLockService;

    @Override
    public List<Long> batchDeleteEntrustAccountConnectionObjects(List<EntrustAccountConnectionObjects> list) {

        if (list != null && list.size() > 0) {
            final List<EntrustAccountConnectionObjects> finalList = list;
            String sql = "DELETE FROM entrust_account_connection_objects WHERE fb_connection_object_id = ? and fb_account_id = ?";
            int[] ids = getJdbcTemplate().batchUpdate(sql, new BatchPreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement ps, int i) throws SQLException {
                    EntrustAccountConnectionObjects ea = finalList.get(i);
                    ps.setObject(1, ea.getFbConnectionObjectId());
                    ps.setObject(2, ea.getFbAccountId());
                }

                @Override
                public int getBatchSize() {
                    return finalList.size();
                }
            });
            List<Long> deleteIds = new ArrayList<>();
            if(ids != null && ids.length >0){
                for(int i= 0; i <ids.length; i++){
                    deleteIds.add(new Long(ids[i]));
                }
            }
            return deleteIds;
        }else{
            return null;
        }
    }


    @Override
    public Integer saveEntrustAccountConnectionObject(EntrustAccountConnectionObjects entrustAccountConnectionObject) {
        String key = CommonConstants.ACCOUNT_CONNECTION_OBJECT_LOCK+entrustAccountConnectionObject.getFbConnectionObjectId()+"-"+entrustAccountConnectionObject.getFbAccountId();
        if(redisDistributedLockService.tryLock(key)){
            try{
                if(this.findEntrustAccountConnectionObjectByFbAccountIdAndFbConnectionObjectId(entrustAccountConnectionObject.getFbAccountId(),entrustAccountConnectionObject.getFbConnectionObjectId())==null){
                    String sql = "INSERT INTO entrust_account_connection_objects (fb_connection_object_id,fb_account_id) VALUES(?,?)";
                    return  getJdbcTemplate().update(sql,entrustAccountConnectionObject.getFbConnectionObjectId(),entrustAccountConnectionObject.getFbAccountId());
                }
            }catch(Exception ex){
                Log.error(ex.getMessage(),ex);
            }finally {
                redisDistributedLockService.unLock(key);
            }
        }
        return 0;
    }

    public EntrustAccountConnectionObjects findEntrustAccountConnectionObjectByFbAccountIdAndFbConnectionObjectId(Long fbAccountId,Long fbConnectionObjectId){
        String sql = "select * from entrust_account_connection_objects where fb_connection_object_id =?  and fb_account_id = ?";
        List<EntrustAccountConnectionObjects>  entrustAccountConnectionObjectses = getJdbcTemplate().query(sql, new Object[]{fbConnectionObjectId, fbAccountId},
                DefaultRowMapper.autoRowMapper(EntrustAccountConnectionObjects.class));
        if(entrustAccountConnectionObjectses!=null && entrustAccountConnectionObjectses.size()>0){
            return entrustAccountConnectionObjectses.get(0);
        }
        return null;
    }

	/** 
	 * @discription
	 * @author giser.yang       
	 * 创建时间 2015年6月29日 下午5:56:51      
	 * @param fbAccountId
	 * @return     
	 * @see com.ndp.fb.rdb.api.EntrustAccountConnectionObjectsRdbService#findEntrustAccountConnectionObjectByFbAccountId(java.lang.Long)     
	 */  
	    
	@Override
	public List<EntrustAccountConnectionObjects> findEntrustAccountConnectionObjectByFbAccountId(
			Long fbAccountId) {
		 String sql = "select * from entrust_account_connection_objects where fb_account_id = ?";
	     return getJdbcTemplate().query(sql, new Object[]{ fbAccountId}, DefaultRowMapper.autoRowMapper(EntrustAccountConnectionObjects.class));
	}


    @Override
    public List<EntrustAccountConnectionObjects> findEntrustAccountsByFbConnectionObjectId(String userId,Long orgId,Long fbconnectionObjectId) {
        String sql = "select distinct eaco.fb_account_id, eaco.fb_connection_object_id, ea.custom_audience_tos  \n" +
                "from \n" +
                "entrust_account_connection_objects eaco, entrust_account ea,\n" +
                "fb_userpermissions_adaccounts fua,\n" +
                "user u,\n" +
                "fb_user fu\n" +
                "where \n" +
                "eaco.fb_account_id = ea.fb_account_id \n" +
                "and eaco.fb_account_id = fua.fb_account_id  \n" +
                "and fua.status = 'ACTIVE' and (role ='ADMIN' or role = 'GENERAL_USER') \n" +
                "and fu.fb_user_id =  fua.fb_user_id\n" +
                "and u.org_id = ? \n" +
                "and fb_connection_object_id = ? \n" +
                "and fua.fb_account_id in (select fb_account_id from fb_userpermissions_adaccounts where fb_user_id  in(select fb_user_id from fb_user fu,user u where ticket = ? and fu.user_id = u.ticket) and status = 'ACTIVE' and (role ='ADMIN' or role = 'GENERAL_USER') ) ";
        return  getJdbcTemplate().query(sql, new Object[]{orgId,fbconnectionObjectId,userId}, DefaultRowMapper.autoRowMapper(EntrustAccountConnectionObjects.class));
    }
}
